// src/main/java/com/fjnu/dao/impl/ArticleDaoImpl.java
package com.fjnu.dao.impl;

import com.fjnu.dao.ArticleDao;
import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.entity.Article;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ArticleDaoImpl implements ArticleDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int insert(Article article) {
        if (article.getUserId() == null || article.getTitle() == null ||
                article.getContent() == null || article.getCategoryId() == null) {
            return 0;
        }

        String sql = "INSERT INTO tb_article(user_id, title, content, status, description, category_id, " +
                "create_time, update_time, support, oppose, recommended, is_top, cover_img) " +
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, article.getUserId(), article.getTitle(), article.getContent(),
                article.getStatus(), article.getDescription(), article.getCategoryId(),
                article.getCreateTime(), article.getUpdateTime(), article.getSupport(),
                article.getOppose(), article.getRecommended(), article.getIsTop(), article.getCoverImg());
    }

    @Override
    public int updateContent(Integer id, String newContent) {
        if (id == null || newContent == null) {
            return 0;
        }
        String sql = "UPDATE tb_article SET content = ?, update_time = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newContent, new Date(), id);
    }

    @Override
    public int updateTitle(Integer id, String newTitle) {
        if (id == null || newTitle == null) {
            return 0;
        }
        String sql = "UPDATE tb_article SET title = ?, update_time = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newTitle, new Date(), id);
    }

    @Override
    public int updateByCondition(Integer id, ArticleConditionDto articleCondition) {
        if (id == null || articleCondition == null) {
            return 0;
        }

        StringBuilder sql = new StringBuilder("UPDATE tb_article SET update_time = ?");
        List<Object> params = new ArrayList<>();
        params.add(new Date());

        if (articleCondition.getUserId() != null) {
            sql.append(", user_id = ?");
            params.add(articleCondition.getUserId());
        }
        if (articleCondition.getTitle() != null) {
            sql.append(", title = ?");
            params.add(articleCondition.getTitle());
        }
        if (articleCondition.getContent() != null) {
            sql.append(", content = ?");
            params.add(articleCondition.getContent());
        }
        if (articleCondition.getStatus() != null) {
            sql.append(", status = ?");
            params.add(articleCondition.getStatus());
        }
        if (articleCondition.getDescription() != null) {
            sql.append(", description = ?");
            params.add(articleCondition.getDescription());
        }
        if (articleCondition.getCategoryId() != null) {
            sql.append(", category_id = ?");
            params.add(articleCondition.getCategoryId());
        }

        sql.append(" WHERE id = ?");
        params.add(id);

        return jdbcTemplate.update(sql.toString(), params.toArray());
    }

    @Override
    public int updateStatus(Integer id, Integer newStatus) {
        if (id == null || newStatus == null || (newStatus != 0 && newStatus != 1)) {
            return 0;
        }
        String sql = "UPDATE tb_article SET status = ?, update_time = ? WHERE id = ?";
        return jdbcTemplate.update(sql, newStatus, new Date(), id);
    }

    @Override
    public int batchUpdateStatus(List<Integer> ids, Integer newStatus) {
        if (ids == null || ids.isEmpty() || newStatus == null || (newStatus != 0 && newStatus != 1)) {
            return 0;
        }

        String sql = "UPDATE tb_article SET status = ?, update_time = ? WHERE id = ?";
        List<Object[]> batchArgs = new ArrayList<>();
        for (Integer id : ids) {
            batchArgs.add(new Object[]{newStatus, new Date(), id});
        }

        int[] results = jdbcTemplate.batchUpdate(sql, batchArgs);
        return results.length;
    }

    @Override
    public int deleteById(Integer id) {
        if (id == null) {
            return 0;
        }
        String sql = "DELETE FROM tb_article WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Article> selectByUserId(Integer userId) {
        if (userId == null) {
            return null;
        }
        String sql = "SELECT * FROM tb_article WHERE user_id = ? ORDER BY create_time DESC";
        try {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class), userId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Article> selectByKeyWord(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return null;
        }
        String sql = "SELECT * FROM tb_article WHERE title LIKE ? OR content LIKE ? ORDER BY create_time DESC";
        String likeKeyword = "%" + keyword + "%";
        try {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class), likeKeyword, likeKeyword);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Article> selectByTimePeriod(Date startTime, Date endTime) {
        StringBuilder sql = new StringBuilder("SELECT * FROM tb_article WHERE 1=1");
        List<Object> params = new ArrayList<>();

        if (startTime != null) {
            sql.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (endTime != null) {
            sql.append(" AND create_time <= ?");
            params.add(endTime);
        }

        sql.append(" ORDER BY create_time DESC");

        try {
            return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(Article.class), params.toArray());
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Article> selectByTag(Integer tagId) {
        if (tagId == null) {
            return null;
        }
        String sql = "SELECT a.* FROM tb_article a " +
                "INNER JOIN tb_article_tag at ON a.id = at.article_id " +
                "WHERE at.tag_id = ? ORDER BY a.create_time DESC";
        try {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class), tagId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Article> selectByCategory(Integer categoryId) {
        if (categoryId == null) {
            return null;
        }
        String sql = "SELECT * FROM tb_article WHERE category_id = ? ORDER BY create_time DESC";
        try {
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class), categoryId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Article insertAndReturnId(Article article) {
        if (article.getUserId() == null || article.getTitle() == null ||
                article.getContent() == null || article.getCategoryId() == null) {
            return null;
        }

        String sql = "INSERT INTO tb_article(user_id, title, content, status, description, category_id, " +
                "create_time, update_time, support, oppose, recommended, is_top, cover_img) " +
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"});
            ps.setInt(1, article.getUserId());
            ps.setString(2, article.getTitle());
            ps.setString(3, article.getContent());
            ps.setInt(4, article.getStatus() != null ? article.getStatus() : 0);
            ps.setString(5, article.getDescription());
            ps.setInt(6, article.getCategoryId());
            ps.setTimestamp(7, new java.sql.Timestamp(article.getCreateTime().getTime()));
            ps.setTimestamp(8, new java.sql.Timestamp(article.getUpdateTime().getTime()));
            ps.setInt(9, article.getSupport() != null ? article.getSupport() : 0);
            ps.setInt(10, article.getOppose() != null ? article.getOppose() : 0);
            ps.setBoolean(11, article.getRecommended() != null ? article.getRecommended() : false);
            ps.setBoolean(12, article.getIsTop() != null ? article.getIsTop() : false);
            ps.setString(13, article.getCoverImg());
            return ps;
        }, keyHolder);

        Number key = keyHolder.getKey();
        if (key != null) {
            article.setId(key.intValue());
            return article;
        }
        return null;
    }
}